package com.zhengqiangblog.blog.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.apache.log4j.Logger;

import com.zhengqiangblog.blog.dao.common.JdbcDaoSupport;
import com.zhengqiangblog.blog.model.Tag;
import com.zhengqiangblog.core.RowMapper;

public class TagDao extends JdbcDaoSupport {

	private static final Logger logger = Logger.getLogger(TagDao.class);

	private TagRowMapper tagRowMapper = new TagRowMapper();

	public TagDao() {
		logger.info("TagDao initializing...");
	}

	public int saveTag(Tag tag) throws Exception {
		String sql = "insert into tag (name) values (?)";
		return this.getJdbcTemplate().update(sql, tag.getName());
	}

	public int deleteTag(int tagId) throws Exception {
		String sql = "delete from tag where id = ?";
		return this.getJdbcTemplate().update(sql, tagId);
	}

	public List<Tag> getTagList() throws Exception {
		String sql = "select id, name from tag";
		return this.getJdbcTemplate().query(sql, tagRowMapper);
	}

	public Tag getTag(int tagId) throws Exception {
		String sql = "select id, name from tag where id = ?";
		return this.getJdbcTemplate().queryForObject(sql, tagRowMapper, tagId);
	}

	public int updateTag(Tag tag) throws Exception {
		String sql = "update tag set name = ? where id = ?";
		return this.getJdbcTemplate().update(sql, tag.getName(), tag.getId());
	}

	private class TagRowMapper implements RowMapper<Tag> {
		@Override
		public Tag mapRow(ResultSet rs, int rowNum) throws SQLException {
			Tag tag = new Tag();
			tag.setId(rs.getInt("id"));
			tag.setName(rs.getString("name"));
			return tag;
		}
	}
}
